﻿using System;
using ZyGame.Execute;
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using ZyGame.Game;
using ZyGame.UI;

namespace ZyGame.Resource
{
    public class SceneLoadRunnable : Runnable
    {
        private Action<float> _progress_callback;

        public static SceneLoadRunnable Create(string name)
        {
            if (Client.Running.TryGetOrCreate(name, out SceneLoadRunnable sceneLoadRunnable))
            {
                return sceneLoadRunnable;
            }

            LoadingWindow loading = Client.Window.GetOrOpen<LoadingWindow>();
            loading.SetText("text", $"Loading [{name}] Scene...");
            sceneLoadRunnable.name = name;
            sceneLoadRunnable.ListenerProgress(loading.UpdateSliderValue);
            sceneLoadRunnable.Execute(sceneLoadRunnable.LoadScene);
            sceneLoadRunnable.Execute(() => { Client.Window.CloseView<LoadingWindow>(); });
            return sceneLoadRunnable;
        }

        IEnumerator LoadScene()
        {
            int disableProgress = 0;
            int toProgress = 0;
            AsyncOperation op = SceneManager.LoadSceneAsync(name);
            op.allowSceneActivation = false;
            while (op.progress < 0.9f)
            {
                toProgress = (int)(op.progress * 100);
                while (disableProgress < toProgress)
                {
                    ++disableProgress;
                    _progress_callback?.Invoke(disableProgress / 100.0f);
                    yield return new WaitForEndOfFrame();
                }
            }

            toProgress = 100;
            while (disableProgress < toProgress)
            {
                ++disableProgress;
                _progress_callback?.Invoke(disableProgress / 100.0f);
                yield return new WaitForEndOfFrame();
            }

            op.allowSceneActivation = true;
            yield return new WaitForSeconds(1);
        }

        public void ListenerProgress(Action<float> action)
        {
            _progress_callback = action;
        }
    }
}